package golib

import (
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
	rds "github.com/go-redis/redis"
)

// Cors 跨域中间件
func Cors(c *gin.Context) {
	c.Header("Access-Control-Allow-Origin", "*")
	c.Header("Access-Control-Allow-Headers", "*")
	c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
	method := c.Request.Method
	if method == "OPTIONS" {
		c.AbortWithStatus(http.StatusNoContent)
		c.Abort()
	}
}

// TokenMiddleware token校验中间件
func TokenMiddleware(c *gin.Context) {
	tenantId := Int64(c.GetHeader("tenantId"))
	redis := Redis()
	cacheKey := "token:" + c.GetHeader("token")
	val := JsonToMap(redis.Get(cacheKey).Val())

	if val["uid"] == nil {
		c.JSON(403, FormatData("请重新登录", c.GetHeader("token"), false))
		c.Abort()
	} else if Int64(val["uid"]) > 0 {
		second := Int64(Conf("session")["expireSecond"])
		redis.ZAdd("user_active", rds.Z{Score: Float64(time.Now().Unix()), Member: val["openid"]}) //活跃用户存入队列
		redis.ExpireAt(cacheKey, time.Now().Add(time.Duration(second)*time.Second))
		c.Set("uid", Int64(val["uid"]))
		c.Set("nickname", val["nickname"])
		c.Set("openid", val["openid"])
		c.Set("tenantId", tenantId)
		c.Next()
	} else {
		c.JSON(403, FormatData("请登录后再操作1", "", false))
		c.Abort()
	}
}

// TokenAndTenantMiddleware token和tenantId校验中间件
func TokenAndTenantMiddleware(c *gin.Context) {
	tenantId := Int64(c.GetHeader("tenantId"))
	redis := Redis()
	cacheKey := "token:" + c.GetHeader("token")
	val := JsonToMap(redis.Get(cacheKey).Val())

	if val["uid"] == nil {
		c.JSON(403, FormatData("请重新登录", c.GetHeader("token"), false))
		c.Abort()
	} else if tenantId == 0 {
		c.JSON(403, FormatData("租户id不能空", "", false))
		c.Abort()
	} else if redis.Get("merge:"+String(val["uid"])).Val() != "" {
		c.JSON(403, FormatData("账号被合并,请重新登录", "4031", false))
		c.Abort()
	} else if Int64(val["uid"]) > 0 {
		second := Int64(Conf("session")["expireSecond"])
		redis.ZAdd("user_active", rds.Z{Score: Float64(time.Now().Unix()), Member: val["openid"]}) //活跃用户存入队列
		redis.ExpireAt(cacheKey, time.Now().Add(time.Duration(second)*time.Second))
		c.Set("uid", Int64(val["uid"]))
		c.Set("nickname", val["nickname"])
		c.Set("openid", val["openid"])
		c.Set("tenantId", tenantId)
		c.Next()
	} else {
		c.JSON(403, FormatData("请登录后再操作2", "", false))
		c.Abort()
	}
}
